package com.jomoo.scs.service.user.impl;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.jomoo.scs.config.WechatAuthProperties;
import com.jomoo.scs.model.user.WechatAuthCodeResponse;
import com.jomoo.scs.model.user.WechatAuthenticationResponse;
import com.jomoo.scs.service.user.UserService;
import com.jomoo.scs.utils.RedisUtils;


@Service
public class UserServiceImpl implements UserService{
	 private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

	  
	    /**
	         *服务器第三方session有效时间，单位秒, 默认1天
	     */
	    private static final Long EXPIRES = 86400L;

	    private RestTemplate wxAuthRestTemplate = new RestTemplate();

	    @Autowired
	    private WechatAuthProperties wechatAuthProperties;

	    @Autowired
	    private RedisUtils redisUtils;
	    
	  /**
	   	* 微信授权
	   */
		@Override
	    public WechatAuthenticationResponse wechatLogin(String code) {
	        WechatAuthCodeResponse response = getWxSession(code);

	        //微信OpenId
	        String wxOpenId = response.getOpenid();
	        //SessionKey 
	        String wxSessionKey = response.getSessionKey();
	        //将微信ID存到数据库


	        Long expires = response.getExpiresIn();
	        //存到redis返回一个key
	        String thirdSession = create3rdSession(wxOpenId, wxSessionKey, expires);
	        return new WechatAuthenticationResponse(thirdSession);
	    }

	    public WechatAuthCodeResponse getWxSession(String code) {
	        LOGGER.info(code);
	        String urlString = "?appid={appid}&secret={srcret}&js_code={code}&grant_type={grantType}";
	        String response = wxAuthRestTemplate.getForObject(
	                wechatAuthProperties.getSessionHost() + urlString, String.class,
	                wechatAuthProperties.getAppId(),
	                wechatAuthProperties.getSecret(),
	                code,
	                wechatAuthProperties.getGrantType());
	        ObjectMapper objectMapper = new ObjectMapper();
	        ObjectReader reader = objectMapper.readerFor(WechatAuthCodeResponse.class);
	        WechatAuthCodeResponse res;
	        try {
	            res = reader.readValue(response);
	        } catch (IOException e) {
	            res = null;
	            LOGGER.error("反序列化失败", e);
	        }
	        LOGGER.info(response);
	        if (null == res) {
	            throw new RuntimeException("调用微信接口失败!");
	        }
	        if (res.getErrcode() != null) {
	            throw new RuntimeException(res.getErrmsg());
	        }
	        res.setExpiresIn(res.getExpiresIn() != null ? res.getExpiresIn() : EXPIRES);
	        return res;
	    }

	    public String create3rdSession(String wxOpenId, String wxSessionKey, Long expires) {
	        String thirdSessionKey = RandomStringUtils.randomAlphanumeric(64);
	        StringBuffer sb = new StringBuffer();
	        sb.append(wxSessionKey).append("#").append(wxOpenId);

	        redisUtils.set(thirdSessionKey, sb.toString(), expires);
	        System.out.println("redis数据库key为:========================>"+thirdSessionKey);
	        System.out.println("redis数据库value为:========================>"+sb.toString());
	        return thirdSessionKey;
	    }


	   
}
